package com.sunlx.product.utils;

import cn.hutool.core.util.ObjectUtil;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * TODO
 *
 * @author Sunluxin
 * @date 2023/1/13 11:27
 */
public class ObjectUtilss {
    /**
     * 对比两个对象的属性是否完全相同
     * @param ob1
     * @param ob2
     * @param ignorFields 忽略字段
     * @return {@link boolean}
     * @author Sunluxin
     * @date 2023/1/16 9:11
    */
    public static <T> boolean equals(T ob1,T ob2,String... ignorFields){
        Field[] fields = ob1.getClass().getDeclaredFields();
        for (Field field :  fields ) {
            if(Arrays.asList(ignorFields).contains(field.getName()))   continue;
            field.setAccessible(true);
            try {
                Object value1 = field.get(ob1);
                Object value2 = field.get(ob2);
                if(!ObjectUtil.equals(value1, value2)){
                    return false;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return true;
    }
    /**
     * 对比两个对象的属性是否只有其中一个字段不同
     * @param ob1
     * @param ob2
     * @param equalFields 对比字段
     * @return {@link boolean}
     * @author Sunluxin
     * @date 2023/1/16 9:11
     */
    public static <T> boolean OnlyColumnNotEquals(T ob1,T ob2,String equalFields){
        Field[] fields = ob1.getClass().getDeclaredFields();
        Boolean r=true;

        for (Field field :  fields ) {
            if(ObjectUtil.equals(equalFields,field.getName()))   continue;
            field.setAccessible(true);
            try {
                Object value1 = field.get(ob1);
                Object value2 = field.get(ob2);
                if(!ObjectUtil.equals(value1, value2)){
                    r= false;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        if(r){
            for (Field field :  fields ) {
                if(ObjectUtil.equals(equalFields,field.getName()))   {
                    field.setAccessible(true);
                    try {
                        Object value1 = field.get(ob1);
                        Object value2 = field.get(ob2);
                        if(ObjectUtil.equals(value1, value2)){
                            r= false;
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }


            }
        }

        return r;
    }

}
